// component/cus-picker/index.js
Component({
  behaviors: ['wx://form-field'],
  //定义外部class名字
  externalClasses: ['checked-class', 'place-class'],
  /**
   * 组件的属性列表
   */
  properties: {
    initvalue: { // 初始值
      type: String,
      value: null //[road_id,area_id,street_id]
    },
    placeholder: { // 空白填充
      type: String,
      value: "please fill out"
    },
    range: { // T=公众、P=管理员
      type: Array,
      value: []
    },
    rangekey: { // T=公众、P=管理员
      type: String,
      value: "rangekey"
    },
    valuekey: {
      type: String,
      value: "valuekey"
    },
    disabled: { // T=公众、P=管理员
      type: Boolean,
      value: false
    },
    width: { // 宽
      type: String,
      value: false
    },
    def: { // 宽
      type: Boolean,
      value: false
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    value: null,
    valueIndex: null,
    widthStyle: ""
  },
  observers: {
    //监听配置文件
    'initvalue': function(value) {
      let that = this;
      setTimeout(()=>{
        this.setValue(value);
      },100)
    },
    'range': function(rangelist) {
      let def = this.data.def;
      let valuekey = this.data.valuekey;
      let value = null;
      let valueIndex = null;
      if (def == true && rangelist.length > 0) {
        value = rangelist[0][valuekey];
        valueIndex = 0;
      }
      this.setData({
        value,
        valueIndex
      })
    },
    'width': function(value) {
      if (value) {
        let widthStyle = "";
        if (value.indexOf("rpx") > -1 || value.indexOf("px") > -1) {
          widthStyle = `width:${value};`
        } else {
          widthStyle = `width:${value}px;`
        }
        this.setData({
          widthStyle
        })
      }
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    bindPickerChange: function(e) {
      let {
        rangekey,
        valuekey,
        range
      } = this.data;
      let index = e.detail.value;
      this.setData({
        valueIndex: index,
        value: range[index][valuekey]
      })
      this.bindchange(range[index][valuekey]);
    },
    bindchange: function(value) {
      value = value || this.data.value;
      this.triggerEvent('change', {
        "value": value
      });
    },
    setValue(value){
      let range = this.data.range || [];
      console.log({value,range});
      let valuekey = this.data.valuekey;
      let valueIndex = null;
      for (var i = 0; i < range.length; i++) {
        if (value === range[i][valuekey]) {
          valueIndex = i;
          break;
        }
      }
      this.setData({
        valueIndex,
        value
      })
    }
  }
})